package com.handong.handserialprogram.module.createmission.recordtask;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.PersonModel;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.model.entities.UploadTaskEntity;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BackStackFragment;
import com.handong.handserialprogram.module.createmission.CreateMissionActivity;
import com.handong.handserialprogram.module.createmission.searchring.SearchRingFragment;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.module.singletask.MissionActivity;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.SystemUtil;
import com.handong.handserialprogram.utils.UserGuideUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.handong.handserialprogram.widget.guideview.Guide;
import com.handong.handserialprogram.widget.guideview.GuideBuilder;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 用户模式
 * RecordTaskFragment：录入任务信息。
 */
public class RecordTaskFragment extends BackStackFragment {

    private static final String TAG = RecordTaskFragment.class.getSimpleName();
    //boolean IsFinish=false;
    //private Vector<FootRingNewEntity> mRingList;
    private LinearLayout mTaskCriminal;
    private LinearLayout mCriminalLayout, mPoliceLayout;

    private TextView mNameTip, mCriminalTip, mPoliceTip, mRouteTip, mCarTip, mMoreInfoTip;

    private UploadTaskEntity mTaskEntity;

    private MaterialDialog mRouteDialog;

    private Guide mGuideInstance;
    private Context context;
    //public SerialPortUtil mSerialPortUtil;

    public RecordTaskFragment() {

    }

    public static RecordTaskFragment newInstance() {
        RecordTaskFragment fragment = new RecordTaskFragment();
        return fragment;
    }

    @Override
    public void onStart() {
        super.onStart();

//        CreateMissionActivity activity=(CreateMissionActivity)getContext();
//        activity.IsFinish=false;
    }

    @Override
    public void onStop() {
        super.onStop();
//        EventBusUtil.unRegister(this);
//        CreateMissionActivity activity=(CreateMissionActivity)getContext();
//        if (!activity.IsFinish)
//        {
//            closeSerialPort();
//        }

    }


    protected void closeSerialPort() {
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        if (activity.mSerialPortUtil != null) {
            activity.mSerialPortUtil.closeSerialPort();
        }
    }

    protected void scanAroundFootRing() {
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        EventBusUtil.register(this);
        activity.mSerialPortUtil = SerialPortUtil.getInstance(getContext());
        activity.mSerialPortUtil.openSerialPortToReadData();
        activity.mSerialPortUtil.updateWorking(false);
    }

    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveFootRing(CopyOnWriteArrayList<FootRingNewEntity> list) {
        CreateMissionActivity activity = (CreateMissionActivity) context;
        if (activity.getmRingList() != null) {
            activity.setmRingList(list);
        }
//        else{
//            activity.setmRingList(new Vector<FootRingNewEntity>());
//        }

    }

    @Subscribe(priority = 98, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {
        switch (response.getResponseCode()) {

            case RingResponse.LOGOUT_ORDER:
                if (response.isSuccess()) {
                    CreateMissionActivity activity = (CreateMissionActivity) getActivity();
                    if (activity != null && activity.getmRingList() != null) {
                        FootRingNewEntity loginOutFootRing = FootRingNewUtil.findFootRingById(activity.getmRingList(), response.getRingID());
                        if (loginOutFootRing != null) {
                            for (PersonEntity personEntity : mTaskEntity.getCriminal()) {
                                if (loginOutFootRing.getCriminalId() != null && loginOutFootRing.getCriminalId().equals(personEntity.getId())) {
                                    personEntity.setSelected(false);
                                }
                            }
                            activity.getmRingList().remove(loginOutFootRing);
                        }
                    }
                }
                break;

            default:
                return;
        }
    }


    @Override
    protected int getContentViewID() {
        return R.layout.fragment_record_task;
    }

    @Override
    protected void initViewByID(View contentView) {
        initHeaderLayout(R.string.record_miss_info, "完成");

        contentView.findViewById(R.id.recordNameLayout).setOnClickListener(this);
        mTaskCriminal = (LinearLayout) contentView.findViewById(R.id.recordTaskCriminal);
        mTaskCriminal.setOnClickListener(this);
        contentView.findViewById(R.id.recordTaskRoute).setOnClickListener(this);
        contentView.findViewById(R.id.recordTaskCar).setOnClickListener(this);
        contentView.findViewById(R.id.recordTaskPolice).setOnClickListener(this);
        contentView.findViewById(R.id.recordTaskMoreInfo).setOnClickListener(this);
        mCriminalLayout = (LinearLayout) contentView.findViewById(R.id.recordCriminalLayout);
        mCriminalTip = (TextView) contentView.findViewById(R.id.recordCriminalTip);
        mPoliceLayout = (LinearLayout) contentView.findViewById(R.id.recordPoliceLayout);
        mNameTip = (TextView) contentView.findViewById(R.id.recordNameTip);
        mPoliceTip = (TextView) contentView.findViewById(R.id.recordPoliceTip);
        mRouteTip = (TextView) contentView.findViewById(R.id.recordRouteTip);
        mCarTip = (TextView) contentView.findViewById(R.id.recordCarTip);
        mMoreInfoTip = (TextView) contentView.findViewById(R.id.recordMoreInfoTip);

        mTaskEntity = new UploadTaskEntity();

        mTaskEntity.setCriminal(new ArrayList<PersonEntity>());
        mTaskEntity.setPolice(new ArrayList<PersonEntity>());
        scanAroundFootRing();
        context = this.getActivity();
    }

    @Override
    public void onClick(View v) {
        if (dispatchDoubleClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.headerOptionLayout://完成
                requestCreateMission();
                break;
            case R.id.recordNameLayout://录入名字
                showInputNameDialog();
                break;
            case R.id.recordTaskCriminal://录入犯人
                addFrag(CriminalFragment.newInstance(mTaskEntity.getCriminal(), true),
                        R.id.createMissionContainer);
                JLog.d(TAG, "CriminalFragment.newInstance(mTaskEntity.getCriminal()).");
                break;
            case R.id.recordTaskRoute://录入线路
                addFrag(CarFragment.newInstance(mTaskEntity.getRoute(), false), R.id.createMissionContainer);
//                requestTaskRoute();
                break;
            case R.id.recordTaskCar://录入车辆
                addFrag(CarFragment.newInstance(mTaskEntity.getCar(), true), R.id.createMissionContainer);
                break;
            case R.id.recordTaskPolice://录入警察
                addFrag(CriminalFragment.newInstance(mTaskEntity.getPolice(), false),
                        R.id.createMissionContainer);
                break;
            case R.id.recordTaskMoreInfo://备注
                showInputMoreInfoDialog();
                break;
            default:
                super.onClick(v);
        }
    }

    /**
     * 录入名字
     */
    private void showInputNameDialog() {
        final EditText editText = new EditText(getContext());
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        editText.setLayoutParams(params);
        editText.setBackgroundDrawable(null);
        editText.setTextSize(17f);
        editText.setHint(R.string.hint_miss_name_tip);
        editText.setGravity(Gravity.LEFT | Gravity.TOP);
        editText.setLines(2);
        editText.setHintTextColor(getContext().getResources().getColor(R.color.bg_gray));

        String buff = mTaskEntity.getName();
        if (!TextUtils.isEmpty(buff)) {
            editText.setText(buff);
            editText.setSelection(buff.length());
        }
        ViewUtil.changeEditTextStatus(editText);

        MaterialDialog dialog = new MaterialDialog.Builder(getContext())
                .title(R.string.dialog_miss_name)
                .customView(editText, true)
                .negativeColorRes(R.color.bg_gray)
                .negativeText(R.string.dialog_negative_text)
                .positiveColorRes(R.color.back_ground_green)
                .positiveText(R.string.dialog_positive_text)
                .neutralText(R.string.option_item_clear)
                .neutralColorRes(R.color.login_warning_bg_color)
                .canceledOnTouchOutside(false)
                .autoDismiss(false)
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (DialogAction.POSITIVE == which) {
                            AppUtil.hideSoftInput(getContext(), dialog.getWindow());
                            String content = editText.getText().toString().trim();
                            mTaskEntity.setName(content);
                            if (TextUtils.isEmpty(content)) {
                                mNameTip.setText(R.string.record_task_tip_not);
                            } else {
                                mNameTip.setText(content);
                            }
                            dialog.dismiss();
                        } else if (DialogAction.NEUTRAL == which) {
                            editText.setText("");
                            //mTaskEntity.setName("");
                            //mNameTip.setText("可选");
                        } else {
                            AppUtil.hideSoftInput(getContext(), dialog.getWindow());
                            dialog.dismiss();
                        }
                    }
                })
                .build();
        dialog.show();
        AppUtil.showSoftInput(editText);
    }

    /**
     * 保存犯人或警察
     *
     * @param type
     */
    public void savePersonList(int type) {
        switch (type) {
            case CriminalFragment.TYPE_CRIMINAL:
                ArrayList<PersonEntity> list = mTaskEntity.getCriminal();
                mCriminalLayout.removeAllViews();
                if (list.isEmpty()) {
                    mCriminalTip.setVisibility(View.VISIBLE);
                } else {
                    mCriminalTip.setVisibility(View.GONE);
                    addImageIcon(mCriminalLayout, list.size(), R.drawable.icon_criminal_photo);
                }
                break;
            case CriminalFragment.TYPE_POLICE:
                ArrayList<PersonEntity> list1 = mTaskEntity.getPolice();
                mPoliceLayout.removeAllViews();
                if (list1.isEmpty()) {
                    mPoliceTip.setVisibility(View.VISIBLE);
                } else {
                    mPoliceTip.setVisibility(View.GONE);
                    addImageIcon(mPoliceLayout, list1.size(), R.drawable.icon_police_photo);
                }
                break;
            default:
                return;
        }
    }

//    public void saveEntityList(Vector<FootRingNewEntity> list)
//    {
//
//        mRingList=list;
//    }

    /**
     * 保存车辆
     */
    public void saveTaskCar(String content, String idName, boolean isCar) {
        if (isCar) {
            mTaskEntity.setCar(content);
            if (!TextUtils.isEmpty(content)) {
                mCarTip.setText(idName);
            } else {
                mCarTip.setText(R.string.record_task_tip_not);
            }
        } else {
            mTaskEntity.setRoute(content);
            if (!TextUtils.isEmpty(content)) {
                mRouteTip.setText(idName);
            } else {
                mRouteTip.setText(R.string.record_task_tip_not);
            }
        }

    }


    /**
     * 添加任务头像
     */
    private void addImageIcon(LinearLayout container, int num, int resID) {
        if (num > 5) {
            num = 5;
        }
        ImageView imageView = null;
        float dpi = SystemUtil.displayMetricsDpi(getContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Math.round(50 * dpi), Math.round(50 * dpi));
        params.leftMargin = Math.round(8 * dpi);
        for (int i = 0; i < num; i++) {
            imageView = new ImageView(getContext());
            imageView.setImageResource(resID);
            imageView.setLayoutParams(params);
            container.addView(imageView, i);
        }
    }

    /**
     * 录入线路
     */
    private void requestTaskRoute() {
        if (mRouteDialog == null) {
            showLoadDialog(getString(R.string.dialog_get_route));
            RequestParams params = new RequestParams();
            params.put("visit", "GetRoute");
            params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
            AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                    JLog.d(TAG, throwable.toString());
                    getRouteError("获取路线失败");
                }

                @Override
                public void onSuccess(int i, Header[] headers, String s) {
                    JLog.d(TAG, s);
                    if (TextUtils.isEmpty(s) || s.length() < 15) {
                        getRouteError("获取路线失败");
                    }
                    Gson gson = new Gson();
                    PersonModel model = gson.fromJson(s, PersonModel.class);
                    if (model.isSuccess()) {
                        getRouteSuccess(model.getList());
                    } else {
                        getRouteError(model.getReason());
                    }
                }
            });
        } else {
            if (TextUtils.isEmpty(mTaskEntity.getRoute())) {
                mRouteDialog.setSelectedIndex(-1);
            }
            ViewUtil.removeHomeKeyListener(mRouteDialog);
        }
    }

    /**
     * 录入线路成功
     */
    private void getRouteSuccess(ArrayList<PersonEntity> list) {
        int len = list.size();
        String[] itemName = new String[len];
        String[] itemCode = new String[len];
        int checked = -1;
        String code = mTaskEntity.getRoute();
        PersonEntity entity = null;
        for (int i = 0; i < len; i++) {
            entity = list.get(i);
            itemName[i] = entity.getName();
            itemCode[i] = entity.getId();
            if (!TextUtils.isEmpty(code) && entity.getId().equals(code)) {
                checked = i;
            }
        }
        dismissLoadingDialog();
        showRouteDialog(itemName, itemCode, checked);
    }

    private void getRouteError(String reason) {
        dismissLoadingDialog();
        AppUtil.showShortToast(getContext(), reason);
    }

    /**
     * 选择线路
     */
    private void showRouteDialog(String[] nameArr, final String[] codeArr, int checked) {
        if (mRouteDialog == null) {
            mRouteDialog = new MaterialDialog.Builder(getContext())
                    .title(R.string.record_route_title)
                    .items(nameArr)
                    .canceledOnTouchOutside(false)
                    .widgetColorRes(R.color.colorPrimary)
                    .itemsCallbackSingleChoice(checked, new MaterialDialog.ListCallbackSingleChoice() {
                        @Override
                        public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                            if (-1 == which) {
                                return true;
                            }
                            mTaskEntity.setRoute(codeArr[which]);
                            mRouteTip.setText(text);
                            return true;
                        }
                    })
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText(R.string.dialog_positive_text)
                    .negativeColorRes(R.color.bg_gray)
                    .negativeText(R.string.dialog_negative_text)
                    .neutralColorRes(R.color.login_warning_bg_color)
                    .neutralText(R.string.option_item_reset)
                    .onNeutral(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mTaskEntity.setRoute("");
                            mRouteTip.setText(R.string.record_task_tip_not);
                            dialog.setSelectedIndex(-1);
                        }
                    })
                    .build();
        }
        ViewUtil.removeHomeKeyListener(mRouteDialog);
    }

    /**
     * 添加备注
     */
    private void showInputMoreInfoDialog() {
        final EditText editText = new EditText(getContext());
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        editText.setLayoutParams(params);
        editText.setBackgroundDrawable(null);
        editText.setHint(R.string.hint_more_info);
        editText.setTextSize(17f);
        editText.setGravity(Gravity.LEFT | Gravity.TOP);
        editText.setLines(3);
        editText.setHintTextColor(getContext().getResources().getColor(R.color.bg_gray));

        String buff = mTaskEntity.getDescribe();
        if (!TextUtils.isEmpty(buff)) {
            editText.setText(buff);
            editText.setSelection(buff.length());
        }
        ViewUtil.changeEditTextStatus(editText);

        MaterialDialog dialog = new MaterialDialog.Builder(getContext())
                .title(R.string.dialog_title_more_info)
                .customView(editText, true)
                .negativeColorRes(R.color.bg_gray)
                .negativeText(R.string.dialog_negative_text)
                .positiveColorRes(R.color.back_ground_green)
                .positiveText(R.string.dialog_positive_text)
                .neutralText(R.string.option_item_clear)
                .neutralColorRes(R.color.login_warning_bg_color)
                .canceledOnTouchOutside(false)
                .autoDismiss(false)
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (DialogAction.POSITIVE == which) {
                            AppUtil.hideSoftInput(getContext(), dialog.getWindow());
                            String content = editText.getText().toString().trim();
                            mTaskEntity.setDescribe(content);
                            if (TextUtils.isEmpty(content)) {
                                mMoreInfoTip.setText(R.string.record_task_tip_not);
                            } else {
                                mMoreInfoTip.setText(content);
                            }
                            dialog.dismiss();
                        } else if (DialogAction.NEUTRAL == which) {
                            editText.setText("");
                            mMoreInfoTip.setText(R.string.record_task_tip_not);
                            mTaskEntity.setDescribe("");
                        } else {
                            AppUtil.hideSoftInput(getContext(), dialog.getWindow());
                            dialog.dismiss();
                        }
                    }
                })
                .build();
        dialog.show();
        AppUtil.showSoftInput(editText);
    }


    @Override
    protected boolean onBackClicked() {

        if (mGuideInstance != null) {
            mGuideInstance.dismiss();
            return true;
        }
        if (!mTaskEntity.isEmpty()) {
            MaterialDialog dialog = new MaterialDialog.Builder(getContext())
                    .title(R.string.dialog_title_careful)
                    .content(R.string.dialog_exit_tip)
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText(R.string.dialog_positive_exit)
                    .negativeColorRes(R.color.bg_gray)
                    .negativeText(R.string.dialog_negative_text)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            mTaskEntity = null;
                            //removeFragment(null);
                            //removeFrag(null);
                            getActivity().finish();
                            getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.anim_fade_out);
                            closeSerialPort();
                        }
                    })
                    .build();
            ViewUtil.removeHomeKeyListener(dialog);
            return true;
        }
        getActivity().finish();
        getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.anim_fade_out);
        closeSerialPort();
        return false;
    }

    /**
     * 创建任务
     */
    private void requestCreateMission() {
        final String date = SystemUtil.getDateDetailsString();
        final String title;
        if (TextUtils.isEmpty(mTaskEntity.getName())) {
            title = "[快捷]" + date;

        } else {
            title = "[快捷]" + mTaskEntity.getName();
        }
        showLoadDialog("正在创建任务...");

        RequestParams params = new RequestParams();
        params.put("visit", "IsHasSameMissionTitle");
        params.put("title", title);
        params.put("code", SPUtil.getStringValue(SPUtil.LOGIN_CODE));


        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                JLog.d(TAG, throwable.toString());
                createMissionError("服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, s + SystemUtil.getDateDetailsString());
                if (TextUtils.isEmpty(s) || s.length() < 15) {
                    createMissionError("服务器响应失败");
                    return;
                }
                if (s.length() < 15) {
                    createMissionError("服务器响应失败");
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (jsonObject.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
                        dismissLoadingDialog();
//                        String missID = jsonObject.getString("missId");
//                        createMissionSuccess(missID);
                        Bundle bundle = new Bundle();

                        bundle.putString(KeyConstant.MISSION_NAME, title);
                        bundle.putString(KeyConstant.MISSION_TIME, date);
                        String car = mCarTip.getText().toString();
                        if (getResources().getString(R.string.record_task_tip_not).equals(car)) {
                            bundle.putString(KeyConstant.MISSION_CAR, "暂无");
                        } else {
                            bundle.putString(KeyConstant.MISSION_CAR, car);
                        }
                        //EventBusUtil.unRegister(this);
                        addFrag(SearchRingFragment.newInstance(mTaskEntity, bundle),
                                R.id.createMissionContainer);


                    } else {
                        createMissionError(jsonObject.getString(HttpConstant.FAIL_REASON));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 录入引导图
     */
    public void showChooseCriminalGuide() {
        mGuideInstance = UserGuideUtil.showChooseCriminalGuide(mTaskCriminal, R.id.recordTaskCriminal, getActivity(),
                new GuideBuilder.OnVisibilityChangedListener() {
                    @Override
                    public void onShown() {
                    }

                    @Override
                    public void onDismiss() {
                        mGuideInstance = null;
                    }
                });
    }

    /**
     * 创建任务成功
     */
    private void createMissionSuccess(String missId) {
        dismissLoadingDialog();
        AppUtil.showShortToast(getContext(), "任务创建成功");
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstant.MISSION_ID, missId);
        String date = SystemUtil.getDateDetailsString();
        if (TextUtils.isEmpty(mTaskEntity.getName())) {
            bundle.putString(KeyConstant.MISSION_NAME, "[快捷]" + date);
        } else {
            bundle.putString(KeyConstant.MISSION_NAME, "[快捷]" + mTaskEntity.getName());
        }
        bundle.putString(KeyConstant.MISSION_TIME, date);
        String car = mCarTip.getText().toString();
        if (getResources().getString(R.string.record_task_tip_not).equals(car)) {
            bundle.putString(KeyConstant.MISSION_CAR, "暂无");
        } else {
            bundle.putString(KeyConstant.MISSION_CAR, car);
        }
        CreateMissionActivity activity = (CreateMissionActivity) getActivity();
        activity.openActWithFadeOut(MissionActivity.class, bundle);
    }

    /**
     * 创建任务失败
     */
    private void createMissionError(String reason) {
        dismissLoadingDialog();
        AppUtil.showShortToast(getContext(), reason);
    }

    @Override
    public void onDestroyView() {
        if (mRouteDialog != null && mRouteDialog.isShowing()) {
            mRouteDialog.dismiss();
        }
        mRouteDialog = null;
        super.onDestroyView();
    }
    public void onBackPressed(){
        closeSerialPort();
    }
}
